package xyz.jcat.webflux.sucurity;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
import xyz.jcat.common.auth.AuthConst;
import xyz.jcat.security.UserRoleAuthenticationToken;

import java.util.Objects;

/**
 * 请求头设置userId信息
 */
@Slf4j
public class UserInfoHeaderSettingWebFilter  implements WebFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        log.info("come in UserInfoHeaderSettingWebFilter");
        ServerHttpRequest request = exchange.getRequest();
        ServerWebExchange.Builder exchangeBuilder = exchange.mutate();
        return ReactiveSecurityContextHolder.getContext()
                .map(SecurityContext::getAuthentication)
                .defaultIfEmpty(new UserRoleAuthenticationToken())
                .flatMap(authentication -> {
                    UserRoleAuthenticationToken token = (UserRoleAuthenticationToken)authentication;
                    if(token.isAuthenticated()) {
                        ServerHttpRequest newRequest = request.mutate()
                                .header(AuthConst.HEADER_USER_ID, token.getUserId().toString()).build();
                        ServerWebExchange newExchange = exchangeBuilder.request(newRequest).build();
                        return chain.filter(newExchange);
                    }
                    return chain.filter(exchange);
                });
    }

}
